﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lyon.Util.Helper
{
    public static class ByteHelper
    {
        /// <summary>
        /// 将字节转换为16进制
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string ToHex(this byte b)
        {
            if (b == null) return "";
            return b.ToString("X2");
        }

        /// <summary>
        /// 将字节序列转换为16进制
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHex(this IEnumerable<byte> bytes)
        {
            var sb = new StringBuilder();
            foreach (byte b in bytes)
            {
                sb.Append(b.ToHex()).Append(" ");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 将字节数组转为整型，待测，string？非法？
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static int ToInt(this byte[] value, int startIndex)
        {
            if (value == null) return 0;
            if (value.Length == 0) return 0;
            return BitConverter.ToInt32(value, startIndex);
        }

        /// <summary>
        /// 将字节数组转换为制定编码字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string Decode(this byte[] data, Encoding encoding)
        {
            return encoding.GetString(data);
        }
    }
}
